package com.xm.ojbackendjudge.judge;

import cn.hutool.json.JSONUtil;
import com.xm.ojbackendcommon.common.ErrorCode;
import com.xm.ojbackendcommon.exception.BusinessException;
import com.xm.ojbackendjudge.judge.codesandbox.CodeSandbox;
import com.xm.ojbackendjudge.judge.codesandbox.CodeSandboxFactory;
import com.xm.ojbackendjudge.judge.codesandbox.CodeSandboxProxy;
import com.xm.ojbackendjudge.judge.strategy.JudgeContext;
import com.xm.ojbackendmodel.model.codesandbox.ExecuteCodeRequest;
import com.xm.ojbackendmodel.model.codesandbox.ExecuteCodeResponse;
import com.xm.ojbackendmodel.model.codesandbox.JudgeInfo;
import com.xm.ojbackendmodel.model.dto.question.JudgeCase;
import com.xm.ojbackendmodel.model.entity.Question;
import com.xm.ojbackendmodel.model.entity.QuestionSubmit;
import com.xm.ojbackendmodel.model.enums.QuestionSubmitStatusEnum;
import com.xm.ojbackendservice.service.QuestionFeignClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class JudgeServiceImpl implements JudgeService{

    @Resource
    private QuestionFeignClient questionFeignClient;

    @Resource
    private JudgeManager judgeManager;

    @Value("${codesandbox.value:example}")
    private String type;

    @Override
    public QuestionSubmit doJudge(long questionSubmitId) {

        //1. 获取信息 预处理提交题目是否有问题
        QuestionSubmit questionSubmit = questionFeignClient.getQuestionSubmitById(questionSubmitId);
        if (questionSubmit == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "提交题目为空");
        }
        Long questionId = questionSubmit.getQuestionId();
        if (questionId == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "题目为空");
        }
        Question question = questionFeignClient.getQuestionById(questionId);
        //2. 更改提交题目状态
        if (!questionSubmit.getStatus().equals(QuestionSubmitStatusEnum.WAITING.getValue())){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "题目正在判题中");
        }
        QuestionSubmit questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.RUNNING.getValue());
        boolean result = questionFeignClient.updateQuestionSubmitById(questionSubmitUpdate);
        if (!result){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目状态更新失败");
        }

        //3. 提交沙箱
        //工厂模式
        CodeSandbox codeSandbox = CodeSandboxFactory.newInstance(type);
        //代理模式
        codeSandbox = new CodeSandboxProxy(codeSandbox);
        String code = questionSubmit.getCode();
        String language = questionSubmit.getLanguage();
        String judgeCase = question.getJudgeCase();
        //获取输入用例
        List<JudgeCase> judgeCaseList = JSONUtil.toList(judgeCase, JudgeCase.class);
        List<String> inputList = judgeCaseList.stream().map(JudgeCase::getInput).collect(Collectors.toList());
        ExecuteCodeRequest request = ExecuteCodeRequest.builder()
                .code(code)
                .language(language)
                .inputList(inputList)
                .build();
        ExecuteCodeResponse executeCodeResponse = codeSandbox.executeCode(request);
        List<String> outputList = executeCodeResponse.getOutputList();

        //4. 根据沙箱结果判断是否提交正确
        JudgeContext judgeContext = new JudgeContext();
        judgeContext.setJudgeInfo(executeCodeResponse.getJudgeInfo());
        judgeContext.setInputList(inputList);
        judgeContext.setOutputList(outputList);
        judgeContext.setQuestion(question);
        judgeContext.setJudgeCaseList(judgeCaseList);
        judgeContext.setQuestionSubmit(questionSubmit);

        //策略模式
        JudgeInfo judgeInfo = judgeManager.doJudge(judgeContext);

        //修改数据库的判题结果

        questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.SUCCESS.getValue());
        questionSubmitUpdate.setJudgeInfo(JSONUtil.toJsonStr(judgeInfo));
        result = questionFeignClient.updateQuestionSubmitById(questionSubmitUpdate);
        if (!result){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目状态更新失败");
        }
        QuestionSubmit resultQuestionSubmit = questionFeignClient.getQuestionSubmitById(questionSubmitId);
        return resultQuestionSubmit;
    }
}
